<?php
/**
 * Created by PhpStorm.
 * User: Sixstar-Peter
 * Date: 2019/3/29
 * Time: 21:32
 */

class Round
{
    /**
     * 根据上一次访问地址得到当前的访问地址
     */
    protected static  $lastIndex=0; 

    public static function select(array $list){
        $currentIndex = self::$lastIndex;//当前index
        $url = $list[$currentIndex];

        if($currentIndex+1 > count($list)-1){
            self::$lastIndex = 0;
        }else{
            self::$lastIndex++;
        }

        return $url; //返回当前url
    }

    public static function weight(array $list){
        $sum = 0;   //总的权重值
        
        foreach ($list as $key => $value) {
            $sum += $value['weight'];
            $list[$key]['range'] = $sum;
        }

        $rand = mt_rand(0, $sum);
        // var_dump($rand);
        foreach ($list as $key => $value) {
            if($rand <= $value['range']){
                return $value['ip'];
            }
        }
    }
}

$ipList = [
    '192.168.30.10:9800',
    '192.168.30.10:9801',
    '192.168.30.10:9802',
];

$weightList = [
    ['ip' => '192.168.30.10:9800', 'weight' => 1],
    ['ip' => '192.168.30.10:9801', 'weight' => 2],
    ['ip' => '192.168.30.10:9802', 'weight' => 3],
];



while (true) {
    var_dump(Round::select($ipList));
    // var_dump(Round::weight($weightList));
    sleep(1);
}